<template>
  <!--答题，问卷页面 -->
  <div class="schoolProblemPage">
    <MyHead
      title="知识竞答活动"
      style="background-color: rgba(248, 248, 248, 1); font-size: 18px"
    ></MyHead>
    <div class="box">
      <div class="theme-box">{{ theme }}</div>
      <van-form @submit="nextSubmit" @failed="onFailed" ref="form">
        <div v-for="(item, index) in questionList" :key="index">
          <div class="round-box flexc" style="z-index: 0;">
            {{ quesIndex + 1 }}/{{ questionList.length }}
          </div>

          <div v-if="quesIndex == index" class="from-box">
            <!-- 单选 0-->
            <div v-if="item.type == '0'">
              <div class="xuanxiang">
                <span class="serial-number">单选题</span>
                <span>{{ item.title }}</span>
              </div>
              <van-field
                :name="item.name"
                :rules="[{ required: true, message: '至少选择一项' }]"
              >
                <template #input>
                  <van-radio-group
                    v-model="form[item.id].ans"
                    @change="changeValue(item)"
                    :name="item.id"
                  >
                    <div
                      v-for="(v, i) in item.option"
                      :key="i"
                      style="display: flex; line-height: 40px"
                    >
                      <div
                        class="radio-style"
                        :style="
                          v.id === form[item.id].ans
                            ? 'border:1px solid #E21B1B ;background-color:#FFF4F4;'
                            : 'border:1px solid #BBBBBB;background-color:#ffffff  '
                        "
                      >
                        <van-radio
                          :name="v.id"
                          :value="v.id"
                          checked-color="#E21B1B"
                          icon-size="14px"
                        >
                          <span class="line_height30"
                            >{{ v.letter }}.{{ v.title }}</span
                          >
                        </van-radio>
                      </div>
                      <div v-if="v.is_fill == 1">
                        <van-field
                          v-model="form[item.id]['text'][v.id]"
                          :rules="[
                            {
                              validator:
                                form[item.id]['ans'] == v.id
                                  ? v.must_fill == 1
                                    ? mustByData
                                    : () => true
                                  : () => true,
                              message: '',
                            },
                          ]"
                          :name="form[item.id][v.id]"
                          :disabled="form[item.id]['ans'] != v.id"
                          class="border"
                          placeholder="请输入内容"
                        ></van-field>
                      </div>
                    </div>
                  </van-radio-group>
                </template>
              </van-field>
            </div>
            <!-- 多选 1 -->
            <div v-if="item.type == 1">
              <div class="xuanxiang">
                <span class="serial-number">多选题</span>
                <span> {{ item.title }}</span>
              </div>
              <van-field
                :name="item.name"
                :rules="[{ required: true, message: '至少选择一项' }]"
              >
                <template #input>
                  <van-checkbox-group v-model="form[item.id].ans">
                    <div
                      v-for="(v, i) in item.option"
                      :key="i"
                      style="display: flex"
                    >
                      <div
                        class="radio-style"
                        :style="
                          form[item.id].ans.includes(v.id)
                            ? 'border:1px solid #E21B1B ;background-color:#FFF4F4;'
                            : 'border:1px solid #BBBBBB;background-color:#ffffff  '
                        "
                      >
                        <van-checkbox
                          @click="chooseCheck(item, form[item.id].ans, v.id)"
                          :name="v.id"
                          :value="v.id"
                          checked-color="#E21B1B"
                          shape="square"
                          icon-size="14px"
                        >
                          <span class="line_height30">
                            {{ v.letter }}{{ v.title }}</span
                          >
                        </van-checkbox>
                      </div>
                      <div v-if="v.is_fill == 1">
                        <van-field
                          v-model="form[item.id]['text'][v.id]"
                          :rules="[
                            {
                              validator:
                                form[item.id]['ans'].indexOf(v.id) > -1
                                  ? v.must_fill == 1
                                    ? mustByData
                                    : () => true
                                  : () => true,
                              message: '',
                            },
                          ]"
                          :disabled="!(form[item.id]['ans'].indexOf(v.id) > -1)"
                          class="border"
                          placeholder="请输入内容"
                        ></van-field>
                      </div>
                    </div>
                  </van-checkbox-group>
                </template>
              </van-field>
            </div>
            <!-- 文本类型 2-->
            <div v-if="item.type == 2">
              <div class="xuanxiang">
                <span class="serial-number">填空题</span>
                <span class="serial_title"> {{ item.title }}</span>
              </div>
              <van-field
                class="textarea_style"
                v-model="form[item.id].ans"
                :name="item.name"
                :type1="item.type"
                :rules="[{ required: true }]"
                autosize
                type="textarea"
                maxlength="100"
                placeholder="请输入"
                show-word-limit
              >
              </van-field>
            </div>
          </div>
          <div style="margin: 16px" class="">
            <van-button
              round
              block
              type="info"
              v-if="quesIndex == index && quesIndex != questionList.length - 1"
              @click="gotonextques(item, index)"
              native-type="button"
              color="#F57373"
              >下一题</van-button
            >
          </div>
        </div>
        <div style="margin-top: 16px">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            color="#F57373"
            style="margin-top: 10px"
            @click="onSubmit"
            v-if="quesIndex == questionList.length - 1"
            >提交</van-button
          >
        </div>
      </van-form>
    </div>

    <van-overlay :show="show">
      <div class="wrapper" @click.stop>
        <div class="block">
          <div class="toast-style">恭喜您！完成全部答题并回答全部正确</div>
          <div class="flexc btn-style">
            <van-button round type="info" color="#F57373 " @click="goTurntable"
              >立即抽奖</van-button
            >
          </div>
        </div>
      </div>
    </van-overlay>

    <van-overlay :show="bshow" class="myregbox">
      <div class="wrapper" @click.stop>
        <div class="block">
          <div class="flexb">
            <div class="title">答题细节分析</div>
            <div>
              <van-icon name="cross" size="20" @click="bshow = false" />
            </div>
          </div>
          <div class="form-style">
            <ul class="item-style">
              <li v-for="(item, index) in questionList" :key="index">
                <p>
                  第{{ index + 1 }}题
                  {{ item.isFlag ? "回答正确" : "回答错误" }}
                </p>
              </li>
            </ul>
              <div class="btn-style">
                <van-button
                    block
                    round
                    type="primary"
                    color="rgb(245, 115, 115)"
                    v-if="!quan"
                    @click="recodemore"
                    >重新答题
                </van-button>
              </div>
            </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      bshow: false,
      quesIndex: 0, // 第一题开始
      value: "",
      showArea: false,
      fieldValue: "",
      form: {},
      type1: "",

      inputValue: "", //选项输入框
      detailId: "", //答卷记录ID
      theme: "",
      isListen: false,
      show: false,

      act_type: "", //活动形式
      q: "",
      questionList: [], //题目相关数据
      openid: $.cookie("openid"), //取值，
      have_prize: "", //是否抽奖:0=否,1=是
      act_type: "", //活动形式：0=无,1=问卷,2=答题(需要比较正确答案)
      have_medal:"",// 是否赠送勋章：0=否，1=是
      quan: true, // 假设全对
    };
  },
  components: {},
  methods: {
    recodemore() {
      this.quesIndex = 0;
      this.bshow = false;
    },
    gotonextques(aitem, index) {
      this.$refs.form
        .validate(aitem.name)
        .then((res) => {
          // 判断是否正确
          if(this.act_type==2){
          for (var key in this.form) {
            var item = this.form[key];
            if (item.qid == aitem.id) {
              if (item.type == 1) {
                // 2个数组对比
                const arrs = [];
                const options = aitem.option;
                for (var a in options) {
                  var kj = options[a];
                  if (item.answer.indexOf(kj.letter) > -1) {
                    arrs.push(kj.id);
                  }
                }
                if (item.ans.sort().join(",") != arrs.sort().join(",")) {
                  this.$dialog.alert({
                    message: "回答错误",
                  });
                }
              } else {
                // 单选
                const options = aitem.option;
                for (var a in options) {
                  var kj = options[a];
                  if (item.answer == kj.letter) {
                    if (item.ans != kj.id) {
                      this.$dialog.alert({
                        message: "回答错误",
                      });
                    };
                  };
                };
              };
            };
          };
          setTimeout(() => {
            this.quesIndex++;
          }, 300);
        }else{
            this.$nextTick(()=>{
              this.quesIndex++;
            });
        };
      }).catch((err) => {});
    },
    onFailed() {
      this.$toast.fail("请选择");
    },
    mustByData(value) {
      if (value) {
        return true;
      } else {
        return false;
      }
    },
    chooseCheck(item, list, id) {
      const v = this.form[item.id];
      if (!_.includes(list, id)) {
        // 取消选择
        delete v["text"][id];
      };
      const arrs = [];
      const options = this.questionList.find((a) => a.id == v.qid).option;
      for (var a in options) {
        var kj = options[a];
        if (v.answer.indexOf(kj.letter) > -1) {
          arrs.push(kj.id);
        };
      };
      let flag = false;
      if (v.ans.sort().join(",") == arrs.sort().join(",")) {
        flag = true;
      } else {
        flag = false;
      }
      this.questionList = this.questionList.map((at) => {
        if (at.id == v.qid) {
          at.isFlag = flag;
        }
        return { ...at };
      });
    },
    changeValue(item) {
      if (item.type == "0") {
        // 单选
        const v = this.form[item.id];
        for (var jk in v) {
          if (jk == "text") {
            for (var kk in v["text"]) {
              if (v["ans"] != kk) {
                delete v["text"][kk];
              }
            };
          };
        };
        const options = this.questionList.find((kj) => kj.id == v.qid).option;
        let flag = false;
        for (var a in options) {
          let tt = options[a];
          if (v.answer == tt.letter && v.ans == tt.id) {
            flag = true;
          };
        };
        this.questionList = this.questionList.map((at) => {
          if (at.id == v.qid) {
            at.isFlag = flag;
          };
          return { ...at };
        });
      } else if (item.type == 1) {
        // 多选
        // for(var key in this.form){
        //     if(item.id==key){
        //         const v = this.form[key]
        //         for(var jk in v){
        //             if(jk=='text'){
        //                 for(var kk in v['text']){
        //                     // 待开发
        //                 }
        //             }
        //         }
        //     }
        // }
        // const v = this.form[item.id]
        // v['ans'].forEach((it, i) => {
        //     for (var key in v['text']) {
        //         if (key == it) {
        //             // return;
        //         } else {
        //         }
        //     }
        // })
      }
    },
    // 全部选项选择完毕后，会触发 finish 事件
    onFinish({ selectedOptions }) {
      this.showArea = false;
      this.fieldValue = selectedOptions.map((option) => option.text).join("/");
      // 用 /裁切
      let dataArray = this.fieldValue.split("/");
      // 取最后一项
      this.fieldValue = dataArray[dataArray.length - 1];
    },

    async nextSubmit(value) {
      // this.$router.push({name:"turntable"})
    },
    getArrDifference(arr1, arr2) {
      return arr1.concat(arr2).filter(function (value, i, arr) {
        return arr.indexOf(value) === arr.lastIndexOf(value);
      });
    },
    async onSubmit() {
      //活动形式：0=无,1=问卷,2=答题(需要比较正确答案)
      if (this.act_type == 2) {
        // 比较正确答案，全部通过，在走提交等后续逻辑
        this.quan = this.questionList.every((item) => item.isFlag);
        if (this.quan) {
          this.$toast("答题Success,准备提交");
          //提交
          let res = await this.$ajax.getCollect({
            q: this.q,
            openid: this.openid,
            form: this.form,
          });
          if (res.code == 1) {
            this.$toast.success(res.msg);
            setTimeout(()=>{
              if (this.have_prize == 1) {
                this.show = true;
              }else{
                this.$router.push({ name: "activityList" });
              }
            },500);
          }else{
            this.$toast.fail(res.msg);
            setTimeout(() => {
              this.$router.push({ name: "activityList" });
            }, 1000);
          }
        } else {
          this.bshow = true;
        }
        // for (var key in this.form) {
        //   var item = this.form[key];
        //   if (item.type == 1) {
        //     // 2个数组对比
        //     const arrs = [];
        //     const options = this.questionList.find((v) => v.id == key).option;
        //     for (var a in options) {
        //       var kj = options[a];
        //       if (item.answer.indexOf(kj.letter) > -1) {
        //         arrs.push(kj.id);
        //       }
        //     }
        //     if (item.ans.sort().join(",") == arrs.sort().join(",")) {
        //       this.quan = true;
        //     }else{
        //       this.quan = false;
        //     }
        //   } else {
        //     // 单选
        //     const options = this.questionList.find((v) => v.id == key).option;

        //     for (var a in options) {
        //       var kj = options[a];
        //       if (item.answer == kj.letter  && item.ans == kj.id ) {
        //         this.quan = true;
        //       }else{
        //         this.quan = false;
        //         return;
        //       }

        //     }
        //   }
        // }
        // if (this.quan) {
        //   this.$toast("答题Success,准备提交");
        // } else {
        //   this.$toast("答案不对,请重新答题");
        // }
      } else {
        // 其他类型的活动形式，正常走
        let res = await this.$ajax.getCollect({
          q: this.q,
          openid: this.openid,
          form: this.form,
        });
        if (res.code == 1) {
          this.$toast.success(res.msg);

          setTimeout(() => {
            if (this.have_prize == 1) {
              this.show = true;
            }else{
              this.$router.push({ name: "activityList"})
            }
          }, 500);
        } else {
          this.$toast.fail(res.msg);
          setTimeout(() => {
            this.$router.push({ name: "activityList" });
          }, 1000);
        };
      };
    },
    /*抽奖*/
    goTurntable() {
      this.$router.push({ name: "turntable", query: { q: this.q,have_medal:this.have_medal } });
    },

    /*活动内容信息(接口)*/
    async getSurveyDetails() {
      let res = await this.$ajax.getActSurveyDetails({
        q: this.q,
        openid: this.openid,
      });
      if (res.code == 1) {
        this.questionList = res.data;

        res.data.forEach((item, index) => {
          this.$set(this.form, [item.id], {});
          this.$set(this.form[item.id], "index", index);
          this.$set(this.form[item.id], "type", item.type);
          this.$set(this.form[item.id], "qid", item.id);
          this.$set(this.form[item.id], "answer", item.answer);
          if (item.type == 1) {
            this.$set(this.form[item.id], "ans", []);
            this.$set(this.form[item.id], "text", {});
          } else {
            this.$set(this.form[item.id], "ans", "");
            this.$set(this.form[item.id], "text", {});
          };
        });
      } else {
        this.$toast.fail(res.msg);
      };
    },
  },
  mounted() {
    // this.getDetailsList(); //问卷列表(题目)

    console.log(this.$refs.countDown);
    this.act_type = this.$route.query.act_type; //活动形式
    this.q = this.$route.query.q; //区域Code-活动ID
    this.have_prize = this.$route.query.have_prize;//抽奖
    this.have_medal = this.$route.query.have_medal ;//勋章
    this.getSurveyDetails();
  },
};
</script>

<style lang="scss" scoped>
.flexb {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.round-box {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 1px solid white;
  position: absolute;
  top: 100px;
  left: 45%;
  background: linear-gradient(to bottom right, #f44336 50%, #b71c1c);
  color: white;
  z-index: 1;
}
.btn-box {
  margin-top: 50px;
}
.radio-style {
  border: 1px solid #bbbbbb;
  width: 300px;
  background-color: rgba(255, 244, 244, 1);
  border-radius: 4px;
  margin-bottom: 10px;
  padding:0 5px 0 10px;
}
.radio-style2 {
  border: 1px solid #e21b1b;
  background-color: #fff4f4;
  width: 300px;
  border-radius: 4px;
  margin-bottom: 10px;
  color: white;
}
.flexc {
  display: flex;
  justify-content: center;
  align-items: center;
}
.display-justcenter {
  display: flex;
  justify-content: center;
  align-items: center;
}

.schoolProblemPage {
  width: 100%;
  min-height: 100vh;
  height: 100%;
  background: #e8e8e8;

  .box {
    background: url("../../assets/images/dt-bg.jpg") no-repeat;
    background-size: 100% 100%;
    width: 100%;
    min-height: 100vh;
    height: 100%;
    padding-top: 40px;
  }

  .theme-box {
    color: #e1372e;
    font-size: 20px;
    font-family: PingFangSC-regular;
    text-align: center;
    font-weight: bold;
  }

  .van-form{
    padding:35px 17px;
    width:100%;
    box-sizing: border-box;
  }
  .from-box {
    line-height: 20px;
    border-radius: 4px;
    background-color: rgba(255, 255, 255, 1);
    width:100%;
    position: relative;

    .xuanxiang {
      padding: 20px !important;
      width: 100%;
      color: rgba(16, 16, 16, 1);
      font-size: 14px;
      font-family: SourceHanSansSC-regular;
      box-sizing: border-box;
      padding: 15px;
      font-weight: bold;
      .serial-number {
        color: white;
        margin-right: 5px;
        letter-spacing: 3px;
        background: #f44336;
        padding: 2px;
      }
      .serial_title {
        margin: auto 0;
        margin-left: 5px;
        padding-right: 10px;
        line-height: 25px;
      }
    }
  }
}

.line_height30 {
  line-height: 30px;
}

// input框样式
.input_style {
  color: white;
  background-color: transparent;
  border: none;
}

.inputbox ::placeholder {
  color: white;
}

// 弹框样式
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  .block {
    width: 312px;
    height: 249px;
    background-color: #fff;
    border-radius: 10px;

    .toast-style {
      font-size: 25px;
      font-weight: bold;
      text-align: center;
      margin: 20px 10px;
    }
    .btn-style {
      margin-top: 50px;
    }
  }
}

// 错误分析
.myregbox {
  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    .block {
      width: 312px;
      height: 200px;
      background-color: #fff;
      border-radius: 10px;
      padding: 15px;
      .title{
        font-size: 20px;
        font-weight: bold;
      }
      .form-style{
        margin-top: 20px;
        font-size: 18px;
        .item-style{
          line-height: 25px;
        }
        .btn-style{
          margin-top: 20px;
        }
      }
    }
  }
}
</style>
